package com.itheima.autoCode.service.strategy.code;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.itheima.autoCode.dto.CodeContext;
import com.itheima.w_util.BootStarterGenerator;
import com.itheima.w_util.FileUtils;
import com.itheima.w_util.FreemarkerUtil;
import com.itheima.w_util.YmlUtils;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
public class CodeGenerater_INTERFACE_DDD extends AbstractCodeGenerater{
    @Override
    public void doInitCode(CodeContext codeContext) {
        String packagePath = codeContext.getProcessParams().getCurPackagePath();
        String resourcesPath = codeContext.getProcessParams().getCurResourcesPath();
        //生成启动类
        initStartClass(codeContext);

        //生成项目所需的配置文件
        initProjectConf(codeContext, resourcesPath);}

    private void initProjectConf(CodeContext codeContext, String resourcesPath) {
        List<File> files = FileUtil.loopFiles(StrUtil.join(File.separator,codeContext.getConf_path(),"conf"));
        files.forEach(item -> {
            FileUtils.copyFile(item, FileUtil.file(resourcesPath),true);
        });

        //生成配置文件
        generateConfigFile(codeContext,resourcesPath);
        codeContext.getProcessParams().setCurResourcesPath(resourcesPath);

    }

    protected void generateConfigFile(CodeContext codeContext, String resourcesPath) {
        Map<String, Object> config = YmlUtils.createEmptyConfig();
        YmlUtils.addNestedConfig(config, "server.port", 10086);
        YmlUtils.addNestedConfig(config, "project.appname", codeContext.getProjectName());

        //数据库相关配置信息
        YmlUtils.addNestedConfig(config, "spring.datasource.url", codeContext.getUrl());
        YmlUtils.addNestedConfig(config, "spring.datasource.username", codeContext.getUser());
        YmlUtils.addNestedConfig(config, "spring.datasource.password", codeContext.getPassword());

        String confFilePath = StrUtil.join(File.separator, resourcesPath, "application.yml");
        YmlUtils.writeToFile(config, confFilePath);

    }

    private void initStartClass(CodeContext codeContext) {
        String packagePath = codeContext.getProcessParams().getCurPackagePath();
        String packageName = StrUtil.join(".", codeContext.getPackages());

        Map<String, Object> dataModel = new HashMap<>();
        dataModel.put("packageName", packageName);
        dataModel.put("className", codeContext.getStartClassName());
        FreemarkerUtil.renderToFile("start/application.ftl", dataModel,
                new File(StrUtil.join(File.separator,packagePath,codeContext.getStartClassName()+".java")));
    }
}
